package cn.ivbao.bobuilder;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import cn.ivbao.project.xtable.Xtable;

import com.ibatis.sqlmap.client.SqlMapClient;
import com.ximpleware.AutoPilot;
import com.ximpleware.VTDGen;
import com.ximpleware.VTDNav;
import com.ximpleware.XMLModifier;

public class BuildCode extends BuildBase{
	
	private static final Log log = LogFactory.getLog(BuildCode.class);
	
	/**
	 * @author yukun
	 * @param args
	 */
	public static void main(String[] args) {
		try {
			SqlMapClient sqlMap = MyAppSqlConfig.getSqlMapInstance();
			
			BuildPojo bp = new BuildPojo();
			bp.setDbtype("hsql");//设置数据库类型
			/*每一个表代表一个模块的主表*/
//			bp.setTname("test");//设置表名
//			bp.setTname("xtable");//设置表名
			bp.setTname("student");//设置表名

			BuildCode bc = new BuildCode();
			bc.setSqlMap(sqlMap);

			bc.getStruct(bp);
			
		} catch (Exception e) {
			e.printStackTrace();
		}
		
	}

	/**
	 * 获得数据表元素方法
	 * @author yukun
	 * @param tablename
	 * @throws SQLException
	 */
	public void getStruct(BuildPojo bp) throws SQLException{
		
		List pojoBoron = new ArrayList();
		List pojoBoronType = new ArrayList();
		//获得数据结构
		List lt = sqlMap.queryForList("buildcode.selectPojo", bp);
		for(Iterator it=lt.iterator();it.hasNext();){
			Map m = (Map)it.next();
			log.debug(m);
			for(Iterator mit = m.entrySet().iterator();mit.hasNext();){
				Map.Entry entry = (Map.Entry) mit.next();
				log.debug(" ### "+entry.getKey()+"~~"+entry.getValue());
				pojoBoron.add(entry.getKey().toString().toLowerCase());//获得数据表字段
				pojoBoronType.add(m.get(entry.getKey()).getClass());
			}//end rof
			break;
		}//end rof
		
		log.debug(" ======== "+pojoBoron);
		log.debug(" ======== "+pojoBoronType);
		log.debug(" ======== "+lt);
		
		//加入结构Map
		Map ts = new HashMap();
		ts.put("tablename", bp.getTname());
		ts.put("pojoBoron", pojoBoron);
		ts.put("pojoBoronType", pojoBoronType);
		ts.put("dbtype", bp.getDbtype());
		
		setTable_struct(ts);
//		//调用pojo生成
//		setPojo();
//		//调用dao生成
//		setDao();
//		//调用action生成
//		setAction();
//		//调用spring生成
//		setSpring();
//		//调用struts生成
//		setStruts();
//		//调用sqlmap生成
//		setSqlMap();
//		//调用html生成
		setHtml();

//		setSpringConfigXml();
//		setStrutsConfigXml();
//		setSqlMapConfigXml();
	}
	
	public void setHtml(){
		try {
		StringBuffer context = new StringBuffer();
		Map ts = getTable_struct();
		String tablename = (String)ts.get("tablename");
		List pojoBoron = (List)ts.get("pojoBoron");

		context.append("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">\r\n");
		context.append("<html>\r\n");
		context.append("	<head>\r\n");
		context.append("		<title>index.html</title>\r\n");
		context.append("\r\n");
		context.append("		<meta http-equiv=\"keywords\" content=\"keyword1,keyword2,keyword3\">\r\n");
		context.append("		<meta http-equiv=\"description\" content=\"this is my page\">\r\n");
		context.append("		<meta http-equiv=\"content-type\" content=\"text/html; charset=UTF-8\">\r\n");
		context.append("		\r\n");
		context.append("		<script type=\"text/javascript\" src=\"../all_scripts.js\"></script>\r\n");
		context.append("\r\n");
		context.append("        <style>body{margin:0;padding:0;background:#f1f1f1;font:70% Arial, Helvetica, sans-serif; color:#555;line-height:150%;text-align:left;}a{text-decoration:none;color:#057fac;}a:hover{text-decoration:none;color:#999;}h1{font-size:140%;margin:0 20px;line-height:80px;}h2{font-size:120%;}#container{margin:0 auto;width:680px;background:#fff;padding-bottom:20px;}#content{margin:0 20px;}p.sig{margin:0 auto;width:680px;padding:1em 0;}form{margin:1em 0;padding:.2em 20px;background:#eee;}</style>\r\n");
		context.append("	</head>\r\n");
		context.append("\r\n");
		context.append("	<body>\r\n");

		context.append("<div id=\"container\">\r\n");
		context.append("<div id=\"content\">\r\n");
		context.append("<div id=\"outputDiv\" name=\"outputDiv\"></div>\r\n");
		context.append("</div>\r\n</div>\r\n");
		context.append("<textarea name=\"table_jst\" id=\"table_jst\" cols=\"70\" rows=\"22\" style=\"display: none\">\r\n");
		context.append("    <table  cellspacing=\"0\" cellpadding=\"0\">\r\n");
//		context.append("	<thead>\r\n");
		context.append("		<tr>\r\n");
		for(int i=0;i<pojoBoron.size();i++){//表头
			String oname = (String)pojoBoron.get(i);
		    context.append("			<th>"+getFirstCharUp(oname)+"</th>\r\n");
		}//end for
		context.append("		</tr>\r\n");
//		context.append("	</thead>\r\n");
//		context.append("	<tfoot>\r\n");
//		context.append("		<tr>\r\n");
//		for(int i=0;i<pojoBoron.size();i++){//表尾
//			String oname = (String)pojoBoron.get(i);
//		    context.append("			<td>"+getFirstCharUp(oname)+"</td>\r\n");
//		}//end for
//		context.append("		</tr>\r\n");
//		context.append("	</tfoot>\r\n");
//		context.append("	<tbody>\r\n");
		context.append("     {for p in recodes}\r\n");
		context.append("	 <tr>\r\n");
		for(int i=0;i<pojoBoron.size();i++){//表体
			String oname = (String)pojoBoron.get(i);
		    context.append("			<td>${p."+oname+"|default:\"\"|capitalize}</td>\r\n");
		}//end for
		context.append("		 </tr>\r\n");
		context.append("     {/for}\r\n");
//		context.append("	</tbody>\r\n");
		context.append("    </table>\r\n");
		context.append("</textarea>\r\n");
		context.append("<script type=\"text/javascript\">\r\n");
		context.append("$.post(\"server/"+tablename+"/"+tablename+"Select.do\", {\r\n");
//		context.append("	\""+tablename+".id\" : 1\r\n");//初始化时传递条件取消
		context.append("}, function cb(o) {\r\n");
		context.append("	var result = TrimPath.processDOMTemplate(\"table_jst\", eval(\"({\\\"recodes\\\":\"+o.toString()+\"})\"));\r\n");
		context.append("	TrimPath.reInnerHTML(\"outputDiv\", result);\r\n");
		context.append("});\r\n");
		context.append("</script>\r\n");
		
		context.append("	</body>\r\n");
		context.append("</html>\r\n");

		// 获得项目路径
		String path = getClass().getProtectionDomain().getCodeSource()
				.getLocation().getPath();
		if (path.indexOf("WEB-INF") > 0) {
			path = path.substring(0, path.indexOf("/WEB-INF") + 8);
		}
		String fileName = path + "/../server/"+tablename+"/index.html";
		
		log.info("setHtml's file is building : "+fileName);
		log.debug(context);
		//输出outFile Pojo
		writeFile(context.toString(), fileName, true, false);
		} catch (Exception e) {
			e.printStackTrace();
		}
		
	}
	/**
	 * 写入pojo类
	 * @author yukun
	 * @param pojoBoron
	 * @param pojoBoronType
	 */
	public void setPojo(){
		try {
			StringBuffer context = new StringBuffer();
			
			Map ts = getTable_struct();
			String tablename = (String)ts.get("tablename");
			List pojoBoron = (List)ts.get("pojoBoron");
			List pojoBoronType = (List)ts.get("pojoBoronType");
			
			context.append("package cn.ivbao.project."+tablename+";\n\n");
			
			context.append("public class "+getFirstCharUp(tablename)+" {\n\n");
			for(int i=0;i<pojoBoron.size();i++){
				String oname = (String)pojoBoron.get(i);
				Class oclass = (Class)pojoBoronType.get(i);
				
				context.append(oclass.getName()+" "+oname+";\n\n");
				context.append("public "+oclass.getName()+" get"+getFirstCharUp(oname)+"() {\n\n return "+oname+";\n\n}\n\n");
				context.append("public void set"+getFirstCharUp(oname)+"("+oclass.getName()+" "+oname+") {\n\n this."+oname+" = "+oname+";\n\n}\n\n");
				
			}//end rof
			context.append("\n}");
			// 获得项目路径
			String path = getClass().getProtectionDomain().getCodeSource()
					.getLocation().getPath();
			if (path.indexOf("WEB-INF") > 0) {
				path = path.substring(0, path.indexOf("/WEB-INF") + 8);
			}
			String fileName = path + "/../../src/cn/ivbao/project/"+tablename+"/"+getFirstCharUp(tablename)+".java";
			
			log.info("setPojo's file is building : "+fileName);
			log.debug(context);
			//输出outFile Pojo
			writeFile(context.toString(), fileName, true, false);

		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * 写入dao类
	 * @author yukun
	 */
	public void setDao(){
		try {
		StringBuffer context = new StringBuffer();
		
		Map ts = getTable_struct();
		String tablename = (String)ts.get("tablename");
		List pojoBoron = (List)ts.get("pojoBoron");
		List pojoBoronType = (List)ts.get("pojoBoronType");
		
		context.append("package cn.ivbao.project."+tablename+";\n\n");
		
		context.append("import java.util.List;\n");
		context.append("import org.apache.commons.logging.Log;\n");
		context.append("import org.apache.commons.logging.LogFactory;\n");
		context.append("import cn.ivbao.daos.BaseDao;\n");

		context.append("public class "+getFirstCharUp(tablename)+"Dao extends BaseDao {\n\n");
		context.append("private static final Log log = LogFactory.getLog("+getFirstCharUp(tablename)+"Dao.class);\n\n");
		//查询
		context.append("public List select(Object parameterObject){\n");
		context.append("	List lt = this.getSqlMapClientTemplate().queryForList(\""+tablename+".select\", parameterObject);\n");
		context.append("	log.debug(lt);\n");
		context.append("	return lt;\n");
		context.append("}\n");
		//写入
		context.append("public Object add(Object parameterObject){\n");
		context.append("	Object lt = this.getSqlMapClientTemplate().insert(\""+tablename+".insert\", parameterObject);\n");
		context.append("	log.debug(lt);\n");
		context.append("	return lt;\n");
		context.append("}\n");
		
		context.append("\n}");
		// 获得项目路径
		String path = getClass().getProtectionDomain().getCodeSource()
				.getLocation().getPath();
		if (path.indexOf("WEB-INF") > 0) {
			path = path.substring(0, path.indexOf("/WEB-INF") + 8);
		}
		String fileName = path + "/../../src/cn/ivbao/project/"+tablename+"/"+getFirstCharUp(tablename)+"Dao.java";
		
		log.info("setDao's file is building : "+fileName);
		log.debug(context);
		//输出outFile Pojo
		writeFile(context.toString(), fileName, true, false);

		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * 写入action类
	 * @author yukun
	 */
	public void setAction(){
		try {
			StringBuffer context = new StringBuffer();
			
			Map ts = getTable_struct();
			String tablename = (String)ts.get("tablename");
			List pojoBoron = (List)ts.get("pojoBoron");
			List pojoBoronType = (List)ts.get("pojoBoronType");
			
			context.append("package cn.ivbao.project."+tablename+";\n\n");
			
			context.append("import java.util.List;\n");
			context.append("import org.apache.commons.logging.Log;\n");
			context.append("import org.apache.commons.logging.LogFactory;\n");
			context.append("import net.sf.json.JSONArray;\n");
			context.append("import cn.ivbao.actions.BaseAction;\n");
			context.append("import com.opensymphony.xwork2.Action;\n");

			context.append("public class "+getFirstCharUp(tablename)+"Action extends BaseAction {\n\n");
			context.append("private static final Log log = LogFactory.getLog("+getFirstCharUp(tablename)+"Action.class);\n\n");
			
			context.append("private "+getFirstCharUp(tablename)+" "+tablename+" = new "+getFirstCharUp(tablename)+"();\n\n");
			context.append("public "+getFirstCharUp(tablename)+" get"+getFirstCharUp(tablename)+"() {\n");
			context.append("	return "+tablename+";\n");
			context.append("}\n");
			context.append("public void set"+getFirstCharUp(tablename)+"("+getFirstCharUp(tablename)+" "+tablename+") {\n");
			context.append("	this."+tablename+" = "+tablename+";\n");
			context.append("}\n");
			//select
			context.append("public String select() {\n");
			context.append("	cn.ivbao.project."+tablename+"."+getFirstCharUp(tablename)+"Dao td = (cn.ivbao.project."+tablename+"."+getFirstCharUp(tablename)+"Dao) this.getBean(\""+tablename+"Dao\");\n");
			context.append("	List lt = td.select("+tablename+");\n");
			context.append("	for(int i=0;i<lt.size();i++){\n");
			context.append("		"+tablename+" = ("+getFirstCharUp(tablename)+")lt.get(i);\n");
			context.append("	}\n");
			context.append("	JSONArray json = JSONArray.fromObject(lt);//List生成JSON对象\n");
			context.append("	toInStream(json.toString());//将生成的JSON对象转成InputStream\n");
			context.append("	log.debug(json.toString());\n");
			context.append("	return Action.SUCCESS;\n");
			context.append("}\n");
			//insert
			context.append("public String add() {\n");
			context.append("	cn.ivbao.project."+tablename+"."+getFirstCharUp(tablename)+"Dao td = (cn.ivbao.project."+tablename+"."+getFirstCharUp(tablename)+"Dao) this.getBean(\""+tablename+"Dao\");\n");
			context.append("	Object lt = td.add("+tablename+");\n");
			context.append("	JSONArray json = JSONArray.fromObject(lt);//List生成JSON对象\n");
			context.append("	toInStream(json.toString());//将生成的JSON对象转成InputStream\n");
			context.append("	log.debug(json.toString());\n");
			context.append("	return Action.SUCCESS;\n");
			context.append("}\n");

			
			context.append("\n}");
			
			// 获得项目路径
			String path = getClass().getProtectionDomain().getCodeSource()
					.getLocation().getPath();
			if (path.indexOf("WEB-INF") > 0) {
				path = path.substring(0, path.indexOf("/WEB-INF") + 8);
			}
			String fileName = path + "/../../src/cn/ivbao/project/"+tablename+"/"+getFirstCharUp(tablename)+"Action.java";
			
			log.info("setAction's file is building : "+fileName);
			log.debug(context);
			//输出outFile Pojo
			writeFile(context.toString(), fileName, true, false);

		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * 写入spring配置文件
	 * @author yukun
	 */
	public void setSpring(){
		try {
			StringBuffer context = new StringBuffer();
			
			Map ts = getTable_struct();
			String tablename = (String)ts.get("tablename");
			List pojoBoron = (List)ts.get("pojoBoron");
			List pojoBoronType = (List)ts.get("pojoBoronType");
			
			context.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n");
			context.append("<beans xmlns=\"http://www.springframework.org/schema/beans\"\n");
			context.append("xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n");
			context.append("xmlns:jee=\"http://www.springframework.org/schema/jee\"\n");
			context.append("xsi:schemaLocation=\"http://www.springframework.org/schema/beans\n");
			context.append("http://www.springframework.org/schema/beans/spring-beans-2.0.xsd\n");
			context.append("http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-2.0.xsd\">\n");
			context.append("<bean id=\""+tablename+"Action\" class=\"cn.ivbao.project."+tablename+"."+getFirstCharUp(tablename)+"Action\" scope=\"prototype\">\n");
			context.append("</bean>\n");
			context.append("<bean id=\""+tablename+"\" class=\"cn.ivbao.project."+tablename+"."+getFirstCharUp(tablename)+"\" scope=\"prototype\">\n");
			context.append("</bean>\n");
			context.append("<bean id=\""+tablename+"Dao\" class=\"cn.ivbao.project."+tablename+"."+getFirstCharUp(tablename)+"Dao\" scope=\"singleton\" parent=\"sqlMapDao\">\n");
			context.append("</bean>\n");
			context.append("</beans>\n");

			// 获得项目路径
			String path = getClass().getProtectionDomain().getCodeSource()
					.getLocation().getPath();
			if (path.indexOf("WEB-INF") > 0) {
				path = path.substring(0, path.indexOf("/WEB-INF") + 8);
			}
			String fileName = path + "/../../src/cn/ivbao/project/"+tablename+"/spring-"+tablename+".xml";
			
			log.info("setSpring's file is building : "+fileName);
			log.debug(context);
			//输出outFile Pojo
			writeFile(context.toString(), fileName, true, false);

		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * 写入struts配置文件
	 * @author yukun
	 */
	public void setStruts(){
		try {
			StringBuffer context = new StringBuffer();
			
			Map ts = getTable_struct();
			String tablename = (String)ts.get("tablename");
			List pojoBoron = (List)ts.get("pojoBoron");
			List pojoBoronType = (List)ts.get("pojoBoronType");
			
			context.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n");
			context.append("<!DOCTYPE struts PUBLIC \"-//Apache Software Foundation//DTD Struts Configuration 2.0//EN\"\n");
			context.append("        \"http://struts.apache.org/dtds/struts-2.0.dtd\">\n");
			context.append("<struts>\n");
			context.append("	<constant name=\"struts.custom.i18n.resources\" value=\"messageResource\"/>\n");
			context.append("	<include file=\"struts-default.xml\" />\n");
			context.append("	<constant name=\"struts2.i18n.encoding\" value=\"UTF-8\"></constant>\n");
			context.append("	<package name=\""+tablename+"\" extends=\"struts-base\" namespace=\"/server/"+tablename+"\">\n");
			//select
			context.append("		<action name=\""+tablename+"Select\" class=\""+tablename+"Action\" method=\"select\" >\n");
			context.append("		<result type=\"stream\" name=\"success\">\n");
		    context.append("		  <param  name=\"inputName\">inputStream</param>\n");
			context.append("		</result>\n");
			context.append("		</action>\n");
			//insert
			context.append("		<action name=\""+tablename+"Insert\" class=\""+tablename+"Action\" method=\"add\" >\n");
			context.append("		<result type=\"stream\" name=\"success\">\n");
		    context.append("		  <param  name=\"inputName\">inputStream</param>\n");
			context.append("		</result>\n");
			context.append("		</action>\n");
			context.append("	</package>\n");
			context.append("</struts>\n");
			
			// 获得项目路径
			String path = getClass().getProtectionDomain().getCodeSource()
					.getLocation().getPath();
			if (path.indexOf("WEB-INF") > 0) {
				path = path.substring(0, path.indexOf("/WEB-INF") + 8);
			}
			String fileName = path + "/../../src/cn/ivbao/project/"+tablename+"/struts-"+tablename+".xml";
			
			log.info("setStruts's file is building : "+fileName);
			log.debug(context);
			//输出outFile Pojo
			writeFile(context.toString(), fileName, true, false);

		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * 写入sqlmap类（需要判断数据库类型）
	 * @author yukun
	 */
	public void setSqlMap(){
		try {
		StringBuffer context = new StringBuffer();
		
		Map ts = getTable_struct();
		String tablename = (String)ts.get("tablename");
		List pojoBoron = (List)ts.get("pojoBoron");
		List pojoBoronType = (List)ts.get("pojoBoronType");
		
		context.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n");
		context.append("<!DOCTYPE sqlMap PUBLIC \"-//ibatis.apache.org//DTD SQL Map 2.0//EN\" \"http://ibatis.apache.org/dtd/sql-map-2.dtd\" >\n");
		context.append("<sqlMap namespace=\""+tablename+"\" >\n");
		context.append("  <cacheModel id=\"test-cache\" type=\"LRU\">\n");
		context.append("    <flushInterval hours=\"24\"/>\n");
		context.append("    <flushOnExecute statement=\""+tablename+".delete\"/>\n");
		context.append("    <property name=\"size\" value=\"1000\"/>\n");
		context.append("  </cacheModel>\n");
		context.append("  <typeAlias alias=\""+tablename+"\" type=\"cn.ivbao.project."+tablename+"."+getFirstCharUp(tablename)+"\" />\n");
//		context.append("    <!-- 根据主键进行数据查询 -->  \n");
//		context.append("  <select id=\"selectByPk\" resultClass=\""+tablename+"\" parameterClass=\""+tablename+"\" >\n");
//		context.append("    select * from "+tablename+"\n");
//		context.append("    where id=#id:DECIMAL#\n");
//		context.append("  </select>\n");
		  
		context.append("    <!-- 根据主键进行数据删除 -->\n");
		context.append("  <delete id=\"delete\" parameterClass=\""+tablename+"\" >\n");
		context.append("    delete from "+tablename+"\n");
		context.append(getWhereStr(pojoBoron));
		context.append("  </delete> \n");
		  
		context.append("  <select id=\"select\" resultClass=\""+tablename+"\" parameterClass=\""+tablename+"\">\n");
		context.append("    select * from "+tablename+"\n");
		context.append(getWhereStr(pojoBoron));
		context.append("    order by "+getColumnStr(pojoBoron)+"\n");
		context.append("  </select>\n");
		
		context.append("  <select id=\"select_Count\" resultClass=\"java.lang.Integer\" parameterClass=\""+tablename+"\">\n");
		context.append("    select count(1) from (select 1 from "+tablename+"\n");
		
		context.append(getWhereStr(pojoBoron));

		context.append("  </select>\n");
		
		context.append("  <insert id=\"insert\" parameterClass=\""+tablename+"\" > \n");
		if(ts.get("dbtype").equals("hsql")){//判断数据库类型
		context.append("    <selectKey resultClass=\"java.lang.Integer\"  keyProperty=\"id\" >\n");
		context.append("      call identity() \n");//hsql 自增id
		context.append("    </selectKey>\n");
		}else if(ts.get("dbtype").equals("oracle")){
		context.append("	<selectKey resultClass=\"java.lang.Long\" keyProperty=\"id\" > \n");
		context.append("      select sys_seq.nextval as id from dual \n");
		context.append("    </selectKey> \n");
		}
		context.append("    insert into "+tablename+"("+getColumnStr(pojoBoron)+") \n");
		context.append("    values ("+getColumnValueStr(pojoBoron)+") \n");
		context.append("  </insert> \n");
		
		context.append("  <!-- 根据主键进行数据更新 --> \n");
		context.append("  <update id=\"edit\" parameterClass=\""+tablename+"\" > \n");
		context.append("    update "+tablename+" \n");
		context.append("    "+getUpdateSetStr(pojoBoron));
		context.append(getWhereStr(pojoBoron));
		context.append("  </update> \n");

		context.append("  </sqlMap>\n");
		
		// 获得项目路径
		String path = getClass().getProtectionDomain().getCodeSource()
				.getLocation().getPath();
		if (path.indexOf("WEB-INF") > 0) {
			path = path.substring(0, path.indexOf("/WEB-INF") + 8);
		}
		String fileName = path + "/../../src/cn/ivbao/project/"+tablename+"/sqlmap-"+tablename+".xml";
		
		log.info("setSqlmap's file is building : "+fileName);
		log.debug(context);
		//输出outFile Pojo
		writeFile(context.toString(), fileName, true, false);

		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * Xml配置文件修改
	 * @author yukun
	 */
	public void setSpringConfigXml(){
		Map ts = getTable_struct();
		String tablename = (String)ts.get("tablename");
		List pojoBoron = (List)ts.get("pojoBoron");
		List pojoBoronType = (List)ts.get("pojoBoronType");
		// 获得项目路径
		String path = getClass().getProtectionDomain().getCodeSource()
				.getLocation().getPath();
		if (path.indexOf("WEB-INF") > 0) {
			path = path.substring(0, path.indexOf("/WEB-INF") + 8);
		}
		path = path + "/../../src/cn/ivbao/springs/";
		
		String springfile = path+"spring-main.xml";
		
		VTDGen vg = new VTDGen();
		if (vg.parseFile(springfile, true)) {
			VTDNav vn = vg.getNav();
			File fo = new File(springfile);
			FileOutputStream fos;
			try {
				fos = new FileOutputStream(fo);
				AutoPilot ap = new AutoPilot(vn);
				XMLModifier xm = new XMLModifier(vn);
				ap.selectXPath("/beans/import[@resource='classpath:cn/ivbao/project/"+tablename+"/spring-"+tablename+".xml']");
				int i = -1;
				while((i = ap.evalXPath()) != -1){
					xm.remove();
				}
				ap.selectXPath("/beans/import");
				if(ap.evalXPath() != -1)
				xm.insertBeforeElement("<import resource=\"classpath:cn/ivbao/project/"+tablename+"/spring-"+tablename+".xml\" />\n");
				else{
					ap.selectXPath("/beans");
					if(ap.evalXPath() != -1)
						xm.insertAfterHead("\n\n<import resource=\"classpath:cn/ivbao/project/"+tablename+"/spring-"+tablename+".xml\" />\n");
				}
				
				xm.output(fos);
				fos.close();
			}catch (Exception e) {
				e.printStackTrace();
			}
		}else if(vg.parseFile(path+"../bobuilder/template/spring-main.xml", true)){
			VTDNav vn = vg.getNav();
			File fo = new File(springfile);
			FileOutputStream fos;
			try {
				fos = new FileOutputStream(fo);
				AutoPilot ap = new AutoPilot(vn);
				XMLModifier xm = new XMLModifier(vn);
				ap.selectXPath("/beans/import[@resource='classpath:cn/ivbao/project/"+tablename+"/spring-"+tablename+".xml']");
				int i = -1;
				while((i = ap.evalXPath()) != -1){
					xm.remove();
				}
				ap.selectXPath("/beans/import");
				if(ap.evalXPath() != -1)
				xm.insertBeforeElement("<import resource=\"classpath:cn/ivbao/project/"+tablename+"/spring-"+tablename+".xml\" />\n");
				else{
					ap.selectXPath("/beans");
					if(ap.evalXPath() != -1)
						xm.insertAfterHead("\n\n<import resource=\"classpath:cn/ivbao/project/"+tablename+"/spring-"+tablename+".xml\" />\n");
				}
				
				xm.output(fos);
				fos.close();
			}catch (Exception e) {
				e.printStackTrace();
			}
		}// end fi
	}

	/**
	 * Xml配置文件修改
	 * @author yukun
	 */
	public void setStrutsConfigXml(){
		Map ts = getTable_struct();
		String tablename = (String)ts.get("tablename");
		List pojoBoron = (List)ts.get("pojoBoron");
		List pojoBoronType = (List)ts.get("pojoBoronType");
		// 获得项目路径
		String path = getClass().getProtectionDomain().getCodeSource()
				.getLocation().getPath();
		if (path.indexOf("WEB-INF") > 0) {
			path = path.substring(0, path.indexOf("/WEB-INF") + 8);
		}
		path = path + "/../../src/cn/ivbao/struts/";
		
		String springfile = path+"struts-main.xml";
		
		VTDGen vg = new VTDGen();
		if (vg.parseFile(springfile, true)) {
			VTDNav vn = vg.getNav();
			File fo = new File(springfile);
			FileOutputStream fos;
			try {
				fos = new FileOutputStream(fo);
				AutoPilot ap = new AutoPilot(vn);
				XMLModifier xm = new XMLModifier(vn);
				ap.selectXPath("/struts/include[@file='cn/ivbao/project/"+tablename+"/struts-"+tablename+".xml']");
				int i = -1;
				while((i = ap.evalXPath()) != -1){
					xm.remove();
				}
				ap.selectXPath("/struts/include");
				if(ap.evalXPath() != -1)
				xm.insertBeforeElement("<include file=\"cn/ivbao/project/"+tablename+"/struts-"+tablename+".xml\" />\n");
				else{
					ap.selectXPath("/beans");
					if(ap.evalXPath() != -1)
						xm.insertAfterHead("\n\n<include file=\"cn/ivbao/project/"+tablename+"/struts-"+tablename+".xml\" />\n");
				}
				
				xm.output(fos);
				fos.close();
			}catch (Exception e) {
				e.printStackTrace();
			}
		}else if(vg.parseFile(path+"../bobuilder/template/struts-main.xml", true)){
			VTDNav vn = vg.getNav();
			File fo = new File(springfile);
			FileOutputStream fos;
			try {
				fos = new FileOutputStream(fo);
				AutoPilot ap = new AutoPilot(vn);
				XMLModifier xm = new XMLModifier(vn);
				ap.selectXPath("/struts/include[@file='cn/ivbao/project/"+tablename+"/struts-"+tablename+".xml']");
				int i = -1;
				while((i = ap.evalXPath()) != -1){
					xm.remove();
				}
				ap.selectXPath("/struts/include");
				if(ap.evalXPath() != -1)
					xm.insertBeforeElement("<include file=\"cn/ivbao/project/"+tablename+"/struts-"+tablename+".xml\" />\n");
				else{
					ap.selectXPath("/struts");
					if(ap.evalXPath() != -1)
						xm.insertAfterHead("\n\n<include file=\"cn/ivbao/project/"+tablename+"/struts-"+tablename+".xml\" />\n");
				}
				
				xm.output(fos);
				fos.close();
			}catch (Exception e) {
				e.printStackTrace();
			}
		}// end fi
	}
	
	/**
	 * Xml配置文件修改
	 * @author yukun
	 */
	public void setSqlMapConfigXml(){
		Map ts = getTable_struct();
		String tablename = (String)ts.get("tablename");
		List pojoBoron = (List)ts.get("pojoBoron");
		List pojoBoronType = (List)ts.get("pojoBoronType");
		// 获得项目路径
		String path = getClass().getProtectionDomain().getCodeSource()
				.getLocation().getPath();
		if (path.indexOf("WEB-INF") > 0) {
			path = path.substring(0, path.indexOf("/WEB-INF") + 8);
		}
		path = path + "/../../src/";
		
		String springfile = path+"sql-map-config.xml";
		
		VTDGen vg = new VTDGen();
		if (vg.parseFile(springfile, true)) {
			VTDNav vn = vg.getNav();
			File fo = new File(springfile);
			log.debug(springfile);
			FileOutputStream fos;
			try {
				fos = new FileOutputStream(fo);
				AutoPilot ap = new AutoPilot(vn);
				XMLModifier xm = new XMLModifier(vn);
				ap.selectXPath("/sqlMapConfig/sqlMap[@resource='cn/ivbao/project/"+tablename+"/sqlmap-"+tablename+".xml']");
				int i = -1;
				while((i = ap.evalXPath()) != -1){
					xm.remove();
				}
				ap.selectXPath("/sqlMapConfig/sqlMap");
				if(ap.evalXPath() != -1)
				xm.insertBeforeElement("<sqlMap resource=\"cn/ivbao/project/"+tablename+"/sqlmap-"+tablename+".xml\" />\n");
				else{
					ap.selectXPath("/sqlMapConfig/settings");
					if(ap.evalXPath() != -1)
						xm.insertAfterElement("\n\n<sqlMap resource=\"cn/ivbao/project/"+tablename+"/sqlmap-"+tablename+".xml\" />\n");
				}
				
				xm.output(fos);
				fos.close();
			}catch (Exception e) {
				e.printStackTrace();
			}
		}else if(vg.parseFile(path+"cn/ivbao/bobuilder/template/sql-map-config.xml", true)){
			VTDNav vn = vg.getNav();
			File fo = new File(springfile);
			log.debug(springfile);
			FileOutputStream fos;
			try {
				fos = new FileOutputStream(fo);
				AutoPilot ap = new AutoPilot(vn);
				XMLModifier xm = new XMLModifier(vn);
				ap.selectXPath("/sqlMapConfig/sqlMap[@resource='cn/ivbao/project/"+tablename+"/sqlmap-"+tablename+".xml']");
				int i = -1;
				while((i = ap.evalXPath()) != -1){
					xm.remove();
				}
				ap.selectXPath("/sqlMapConfig/sqlMap");
				if(ap.evalXPath() != -1)
					xm.insertBeforeElement("<sqlMap resource=\"cn/ivbao/project/"+tablename+"/sqlmap-"+tablename+".xml\" />\n");
				else{
					ap.selectXPath("/sqlMapConfig/settings");
					if(ap.evalXPath() != -1)
						xm.insertAfterElement("\n\n<sqlMap resource=\"cn/ivbao/project/"+tablename+"/sqlmap-"+tablename+".xml\" />\n");
				}
				
				xm.output(fos);
				fos.close();
			}catch (Exception e) {
				e.printStackTrace();
			}
		}// end fi
	}

	/**
	 * 统一获得sqlmap中的update的set
	 * @author yukun
	 * @param pb
	 * @return
	 */
	public String getUpdateSetStr(List pb){
		String result = null;
		StringBuffer temp = new StringBuffer();
		for(int i=0;i<pb.size();i++){
			temp.append("      <isNotNull prepend=\",\" property=\""+pb.get(i).toString().toLowerCase()+"\"> \n");
			temp.append("      	"+pb.get(i).toString()+" = #"+pb.get(i).toString().toLowerCase()+"# \n");
			temp.append("      </isNotNull> \n");
		}//end rof		
		if(temp != null){
			result = "    <dynamic prepend=\"set\"> \n"+temp+"    </dynamic> \n";
		}//end fi
		return result;
	}
	
	/**
	 * 统一获得sqlmap中的columnsValue
	 * @author yukun
	 * @param pb
	 * @return
	 */
	public String getColumnValueStr(List pb){
		String result = null;
		StringBuffer temp = new StringBuffer();
		for(int i=0;i<pb.size();i++){
			temp.append("#"+pb.get(i).toString().toLowerCase()+"#,");
		}//end rof		
		if(temp != null && temp.length()>0){
			result = temp.substring(0, temp.length()-1);
		}//end fi
		return result;
	}

	/**
	 * 统一获得sqlmap中的columns
	 * @author yukun
	 * @param pb
	 * @return
	 */
	public String getColumnStr(List pb){
		String result = null;
		StringBuffer temp = new StringBuffer();
		for(int i=0;i<pb.size();i++){
			temp.append(pb.get(i).toString().toLowerCase()+",");
		}//end rof	
		log.debug(temp);
		if(temp != null && temp.length()>0){
			result = temp.substring(0, temp.length()-1);
		}//end fi
		return result;
	}
	/**
	 * 统一获得sqlmap中的where条件
	 * @author yukun
	 * @param pb
	 * @return
	 */
	public String getWhereStr(List pb){
		String result = null;
		StringBuffer temp = new StringBuffer();
		for(int i=0;i<pb.size();i++){
			temp.append("      <isNotNull prepend=\"and\" property=\""+pb.get(i).toString().toLowerCase()+"\">\n");
			temp.append("         	"+pb.get(i).toString()+" = #"+pb.get(i).toString().toLowerCase()+"#\n");
			temp.append("      </isNotNull>\n");
		}//end rof
		if(temp!=null){
			result = "    <dynamic prepend=\"where\">\n"+temp.toString()+"    </dynamic>\n";
		}
		return result;
	}
	
	/**
	 * 首字母大写
	 * @author yukun
	 * @param fcustr
	 * @return
	 */
	public String getFirstCharUp(String fcustr){
		return fcustr.substring(0, 1).toUpperCase()+fcustr.substring(1);
	}
	
	/**
	 * 
	 * @author yukun
	 * @param content
	 * @param fileName
	 * @param over
	 * @param append
	 * @return
	 * @throws Exception
	 */
	public static boolean writeFile(String content, String fileName,
			boolean over, boolean append) throws Exception {
		String dirpath;
		if (fileName.indexOf("/") == -1) {
			dirpath = fileName.substring(0, fileName
					.lastIndexOf(File.separator));
		} else {
			dirpath = fileName.substring(0, fileName.lastIndexOf("/"));
		}
		// System.out.println("dirpath=" + dirpath);
		makeDir(dirpath);
		File file = new File(fileName);
		if (file.exists() && !over) {
			return false;
		}
		if (file.isFile()) {
			FileOutputStream fos = new FileOutputStream(file, append);
			fos.write(content.getBytes("UTF-8"));
			fos.flush();
			fos.close();
			fos = null;
			return true;
		} else {
			FileOutputStream fos = new FileOutputStream(file);
			fos.write(content.getBytes("UTF-8"));
			fos.flush();
			fos.close();
			fos = null;
			return true;
		}
	}
	  
	  /**
	   * description
	   * 
	   * @param fileName
	   */
	  public static void makeDir(String fileName)
	  {
	    if (fileName != null)
	    {
	      File file = new File(fileName);
	      // System.out.println("file=" + file);
	      if (!file.getParentFile().exists())
	      {
	        makeDir(file.getParentFile().getPath());
	      }
	      if (!file.exists())
	      {
	        file.mkdir();
	      }
	    }
	  }

}
